package cn.dancepeak.controller;

import cn.dancepeak.domain.Teacher;
import cn.dancepeak.service.impl.TeacherServiceImpl;
import cn.dancepeak.utils.ExcelUtil;
import cn.dancepeak.utils.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/common")
public class CommonController {
    //接收yml里的配置文件：E:\\file\\
    @Value("${file.file-path}")
    private String path;
    @Autowired
    TeacherServiceImpl teacherService;

    @PostMapping("/upload")
    //MultipartFile file  接收前端处传来的文件
    public R upload(MultipartFile file) throws IOException {
        //得到上传文件的全名称加后缀（源文件名）
        String filename = file.getOriginalFilename();
        //为了防止新文件和源文件名字冲突重命名
        //1.取后缀
        String suffix = filename.split("\\.")[1];
        //2.重命名  通过现在的时间戳
        String filePath = path + System.currentTimeMillis() + "." + suffix;
        //准备输出流，把文件写到服务器
        File file1 = new File(filePath);
        //如果文件不存在则创建
        if(!file1.exists()){
            file1.mkdirs();//级联创建
        }
        //上传文件
        file.transferTo(file1);
        return R.ok("上传成功！");
    }


    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //1.设置响应头，告诉浏览器文件下载的名字，附件表示做下载或上传操作
        // attachment:告诉浏览器，以弹框的方式打开我的附件
        response.setHeader("Content-Disposition","attachment; filename=" + fileName);
        String filePath = path + fileName; // D:filel231413241324132412.txt
        FileInputStream inputStream = new FileInputStream(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        //输入流读取到内容之后，需要写入到输出流中即可完成下载
        IOUtils.copy(inputStream,outputStream);
    }


    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //1.查询出老师所有信息
        List<Teacher> teacher = teacherService.getTeacher();
        //2.使用easyPoi工具类导出
        ExcelUtil.exportExcel(teacher,"老师信息","",Teacher.class,"老师信息",response);
    }
}
